<template>
	<div class="card-fill layout-padding" v-loading="loading" element-loading-text="Loading...">
		<el-card shadow="hover" class="layout-padding-auto create-form">
			<el-form ref="formRef" :model="stateData.vmModel" label-width="120px">
				<el-row :gutter="20">
					<el-col :xs="24" :lg="12" class="mb20">
						<el-form-item
							ref="Entity_PersonId_FormItem"
							prop="Entity.PersonId"
							label="Person"
							:rules="[{ required: true, message: 'Person为必填项', trigger: 'blur' }]"
						>
							<el-select v-model="stateData.vmModel.Entity.PersonId" clearable class="width100">
								<el-option v-for="item in stateData.AllSysPersons" :key="item.Value" :value="item.Value" :label="item.Text"></el-option
							></el-select>
						</el-form-item>
					</el-col>
					<el-col :xs="24" :lg="12" class="mb20">
						<el-form-item
							ref="Entity_AttendanceShiftId_FormItem"
							prop="Entity.AttendanceShiftId"
							label="AttendanceShift"
							:rules="[{ required: true, message: 'AttendanceShift为必填项', trigger: 'blur' }]"
						>
							<el-select v-model="stateData.vmModel.Entity.AttendanceShiftId" clearable class="width100">
								<el-option v-for="item in stateData.AllSysAttendanceShifts" :key="item.Value" :value="item.Value" :label="item.Text"></el-option
							></el-select>
						</el-form-item>
					</el-col>
				</el-row>

				<div class="form-section">
					<div class="section-title">
						<i class="_wtmicon _wtmicon-wxbzhanghu"></i>
						<span>基本信息</span>
					</div>

					<el-row :gutter="20">
						<el-col :xs="24" :lg="12" class="mb20">
							<el-form-item
								ref="Entity_ShiftType_FormItem"
								prop="Entity.ShiftType"
								:rules="[{ required: true, message: '班次类型为必填项', trigger: 'blur' }]"
							>
								<template #label>
									<WtmLabelTooltip label="班次类型" tooltip="班次类型：正常上班、请假、调休、替班、换班等" />
								</template>
								<el-select v-model="stateData.vmModel.Entity.ShiftType" clearable class="width100">
									<el-option key="正常上班" value="正常上班" label="正常上班"></el-option>
									<el-option key="请假" value="请假" label="请假"></el-option>
									<el-option key="调休" value="调休" label="调休"></el-option>
									<el-option key="替班" value="替班" label="替班"></el-option>
									<el-option key="换班" value="换班" label="换班"></el-option
								></el-select>
							</el-form-item>
						</el-col>
						<el-col :xs="24" :lg="12" class="mb20">
							<el-form-item
								ref="Entity_ScheduleType_FormItem"
								prop="Entity.ScheduleType"
								:rules="[{ required: true, message: '排班方式为必填项', trigger: 'blur' }]"
							>
								<template #label>
									<WtmLabelTooltip label="排班方式" tooltip="排班方式：自动排班（系统生成）、人工排班（手动调整）" />
								</template>
								<el-select v-model="stateData.vmModel.Entity.ScheduleType" clearable class="width100">
									<el-option key="自动排班" value="自动排班" label="自动排班"></el-option>
									<el-option key="人工排班" value="人工排班" label="人工排班"></el-option
								></el-select>
							</el-form-item>
						</el-col>
						<el-col :xs="24" :lg="12" class="mb20">
							<el-form-item
								ref="Entity_Status_FormItem"
								prop="Entity.Status"
								:rules="[{ required: true, message: '班次状态为必填项', trigger: 'blur' }]"
							>
								<template #label>
									<WtmLabelTooltip label="班次状态" tooltip="班次状态：正常、取消、暂停等" />
								</template>
								<el-select v-model="stateData.vmModel.Entity.Status" clearable class="width100">
									<el-option key="正常" value="正常" label="正常"></el-option>
									<el-option key="取消" value="取消" label="取消"></el-option>
									<el-option key="暂停" value="暂停" label="暂停"></el-option
								></el-select>
							</el-form-item>
						</el-col>
						<el-col :xs="24" :lg="12" class="mb20">
							<el-form-item ref="Entity_Remark_FormItem" prop="Entity.Remark">
								<template #label>
									<WtmLabelTooltip label="备注说明" tooltip="班次的备注说明，如调整原因、特殊安排等" />
								</template>
								<el-input v-model="stateData.vmModel.Entity.Remark" clearable class="width100"></el-input>
							</el-form-item>
						</el-col>
					</el-row>
				</div>

				<el-row :gutter="20">
					<el-col :xs="24" :lg="12" class="mb20">
						<el-form-item ref="Entity_SubstitutePersonId_FormItem" prop="Entity.SubstitutePersonId" label="SubstitutePerson">
							<el-select v-model="stateData.vmModel.Entity.SubstitutePersonId" clearable class="width100">
								<el-option v-for="item in stateData.AllSysPersons" :key="item.Value" :value="item.Value" :label="item.Text"></el-option
							></el-select>
						</el-form-item>
					</el-col>
				</el-row>

				<div class="form-section">
					<div class="section-title">
						<i class="_wtmicon _wtmicon-wxbzhanghu"></i>
						<span>出勤结果</span>
					</div>

					<el-row :gutter="20">
						<el-col :xs="24" :lg="12" class="mb20">
							<el-form-item
								ref="Entity_AttendanceResult_FormItem"
								prop="Entity.AttendanceResult"
								:rules="[{ required: true, message: '出勤结果为必填项', trigger: 'blur' }]"
							>
								<template #label>
									<WtmLabelTooltip label="出勤结果" tooltip="考勤计算后的出勤结果状态" />
								</template>
								<el-select v-model="stateData.vmModel.Entity.AttendanceResult" clearable class="width100">
									<el-option key="未计算" value="未计算" label="未计算"></el-option>
									<el-option key="正常" value="正常" label="正常"></el-option>
									<el-option key="迟到" value="迟到" label="迟到"></el-option>
									<el-option key="早退" value="早退" label="早退"></el-option>
									<el-option key="迟到且早退" value="迟到且早退" label="迟到且早退"></el-option>
									<el-option key="缺卡" value="缺卡" label="缺卡"></el-option>
									<el-option key="旷工" value="旷工" label="旷工"></el-option
								></el-select>
							</el-form-item>
						</el-col>
						<el-col :xs="24" :lg="12" class="mb20">
							<el-form-item ref="Entity_LateMinutes_FormItem" prop="Entity.LateMinutes">
								<template #label>
									<WtmLabelTooltip label="迟到时长(分钟)" tooltip="迟到的分钟数，0表示未迟到" />
								</template>
								<el-input-number v-model="stateData.vmModel.Entity.LateMinutes" clearable class="width100"></el-input-number>
							</el-form-item>
						</el-col>
						<el-col :xs="24" :lg="12" class="mb20">
							<el-form-item ref="Entity_EarlyLeaveMinutes_FormItem" prop="Entity.EarlyLeaveMinutes">
								<template #label>
									<WtmLabelTooltip label="早退时长(分钟)" tooltip="早退的分钟数，0表示未早退" />
								</template>
								<el-input-number v-model="stateData.vmModel.Entity.EarlyLeaveMinutes" clearable class="width100"></el-input-number>
							</el-form-item>
						</el-col>
						<el-col :xs="24" :lg="12" class="mb20">
							<el-form-item ref="Entity_WorkMinutes_FormItem" prop="Entity.WorkMinutes">
								<template #label>
									<WtmLabelTooltip label="有效工时(分钟)" tooltip="计薪或统计口径的有效工作时长，用于工资计算和统计" />
								</template>
								<el-input-number v-model="stateData.vmModel.Entity.WorkMinutes" clearable class="width100"></el-input-number>
							</el-form-item>
						</el-col>
						<el-col :xs="24" :lg="12" class="mb20">
							<el-form-item ref="Entity_MissingPunchCount_FormItem" prop="Entity.MissingPunchCount">
								<template #label>
									<WtmLabelTooltip label="缺卡次数" tooltip="当日缺卡（未打卡）的次数，正常情况下应为0" />
								</template>
								<el-input-number v-model="stateData.vmModel.Entity.MissingPunchCount" clearable class="width100"></el-input-number>
							</el-form-item>
						</el-col>
						<el-col :xs="24" :lg="12" class="mb20">
							<el-form-item
								ref="Entity_IsAbnormal_FormItem"
								prop="Entity.IsAbnormal"
								:rules="[{ required: true, message: '是否异常为必填项', trigger: 'blur' }]"
							>
								<template #label>
									<WtmLabelTooltip label="是否异常" tooltip="是否存在考勤异常（迟到、早退、缺卡、旷工等）" />
								</template>
								<el-select v-model="stateData.vmModel.Entity.IsAbnormal" clearable class="width100">
									<el-option :key="1" :value="true" :label="$t('message._system.common.vm.tips_bool_true')"></el-option>
									<el-option :key="0" :value="false" :label="$t('message._system.common.vm.tips_bool_false')"></el-option>
								</el-select>
							</el-form-item>
						</el-col>
					</el-row>
				</div>
			</el-form>
		</el-card>
	</div>
</template>

<!--suppress JSAnnotator -->
<script setup lang="ts" name="message._system.common.vm.add;false">
import ElMessage from 'element-plus/es/components/message/index';
import { reactive, ref, getCurrentInstance, onMounted, computed, nextTick, ComponentInternalInstance } from 'vue';
import { SysAttendanceRecordApi as api } from '/@/views/hr/sysattendancerecord/api';
import other from '/@/utils/other';
import { ISysAttendanceRecordVm } from '/@/views/hr/sysattendancerecord/api/interface';
import { IViewModel } from '/@/types/common';

const BUTTON_TEXTS = {
	SAVE: '保存',
	SUBMIT: '提交',
	CLOSE: '关闭',
} as const;
const ci = getCurrentInstance() as ComponentInternalInstance;
const loading = ref(false);
const formRef = ref();
const hasSavedOnce = ref(false);
const stateData = reactive<IViewModel<ISysAttendanceRecordVm>>({
	vmModel: {
		Entity: {
			PersonId: null,
			AttendanceShiftId: null,
			ShiftType: '正常上班',
			ScheduleType: '自动排班',
			Status: '正常',
			Remark: null,
			SubstitutePersonId: null,
			AttendanceResult: '未计算',
			LateMinutes: null,
			EarlyLeaveMinutes: null,
			WorkMinutes: null,
			MissingPunchCount: null,
			IsAbnormal: false,
		},
		ActionName: null,
		IsMyApprove: null,
	},
	AllSysPersons: [],
	AllSysAttendanceShifts: [],
});

const hasEntityId = computed(() => {
	const entity = stateData.vmModel.Entity as any;
	return !!(entity && entity.ID);
});
const handleApiResponse = (response: any) => {
	ElMessage.success(ci.proxy?.$t('message._system.common.vm.submittip') || '提交成功');
	emit('refresh');
	loading.value = false;
	closeDialog();
};

const handleError = (error: any) => {
	other.setFormError(ci, error);
	loading.value = false;
};

const handleApiRequest = (apiCall: () => Promise<any>, beforeSubmit: () => void, isSubmit = false) => {
	formRef.value?.validate((valid: boolean) => {
		if (valid) {
			loading.value = true;
			beforeSubmit();
			apiCall()
				.then((response: any) => handleApiResponse(response))
				.catch(handleError);
		}
	});
};
// 取消
const onClose = () => {
	closeDialog();
};

// 保存
const onSave = () => {
	handleApiRequest(
		() => {
			// 创建一个深拷贝，确保新增时不发送无效的 ID 字段
			const submitData = JSON.parse(JSON.stringify(stateData.vmModel));
			if (!submitData.Entity.ID) {
				// 如果没有有效的 ID，删除该字段
				delete submitData.Entity.ID;
			}
			return api().add(submitData);
		},
		() => {},
		false
	);
};

// 加载选择列表数据
const loadData = async () => {
	await Promise.allSettled([
		other.getSelectList('/api/SysAttendanceRecord/GetSysPersons', [], false).then((x) => (stateData.AllSysPersons = x)),
		other.getSelectList('/api/SysAttendanceRecord/GetSysAttendanceShifts', [], false).then((x) => (stateData.AllSysAttendanceShifts = x)),
	]);
};

const initializePageData = () => {
	const wtmdata = ci.attrs['wtmdata'] as any;
	if (wtmdata?.ID) {
		stateData.vmModel.Entity.ID = wtmdata.ID;
		hasSavedOnce.value = true;
	}
};
// 页面加载时
onMounted(async () => {
	loading.value = true;
	initializePageData();

	try {
		// 并行加载选择列表数据
		await loadData();
	} catch (error) {
		other.setFormError(ci, error);
	} finally {
		loading.value = false;
		nextTick(() => {
			setupHeaderButtons();
		});
	}
});

// 定义子组件向父组件传值事件
const emit = defineEmits(['refresh', 'closeDialog', 'updateHeaderButtons']);

// 关闭弹窗
const closeDialog = () => {
	emit('closeDialog');
};

const setupHeaderButtons = () => {
	const headerButtons = [
		{
			text: BUTTON_TEXTS.SUBMIT,
			type: 'primary',
			onClick: onSave,
			visible: true,
		},
		{
			text: BUTTON_TEXTS.CLOSE,
			type: 'default',
			onClick: onClose,
			visible: true,
		},
	];
	emit('updateHeaderButtons', headerButtons);
};
</script>
